import { useState, useEffect } from 'react';
import { Image,Button } from '@douyinfe/semi-ui';
import styles from "./index.module.scss";
import deleteIcon from "@/assets/images/imageEdit/delete.svg";
import download from "@/assets/images/imageEdit/download.svg";

export default function History({ onLayerImageClick, onCompositeClick, layerImages = [], onReorderImages, selectedImageKey }) {

  
  const [selectedIndex, setSelectedIndex] = useState(null);
  
  // 当外部传入selectedImageKey时，同步内部的selectedIndex
  useEffect(() => {
    setSelectedIndex(selectedImageKey);
  }, [selectedImageKey]);
  
  // 如果没有传入layerImages，使用默认的空数组
  // 将图层以reverse顺序显示（最新的在上面）
  const historyImages = layerImages.map((item, arrayIndex) => {
    return {
      id: `layer-${item.id}`, 
      originalIndex: arrayIndex, // 保留原始数组位置，用于与父组件通信
      fileName: item.fileName, // 文件名，更语义化的标识
      src:item.src
    };
  }).reverse(); // 真正reverse数组，让最新的显示在上面
  
  // 为每个显示项添加显示索引，用于拖拽逻辑
  const displayImages = historyImages.map((item, displayIndex) => ({
    ...item,
    displayIndex // 在reverse后的显示索引
  }));

  // 移除handleImageClick函数，因为已经在handleItemClick中直接处理

  const [draggedItem, setDraggedItem] = useState(null);
  const [isDragging, setIsDragging] = useState(false);
  const [dragOverIndex, setDragOverIndex] = useState(null);

  // 鼠标拖拽相关状态
  const [mouseDown, setMouseDown] = useState(false);
  const [dragStartPos, setDragStartPos] = useState({ x: 0, y: 0 });
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [dragPreview, setDragPreview] = useState({ show: false, x: 0, y: 0, content: null });
  const dragThreshold = 5; // 拖拽阈值，避免误触

  const handleMouseDown = (e, index) => {
    // 只处理左键点击
    if (e.button !== 0) return;
    
    e.preventDefault();
    setMouseDown(true);
    setDragStartPos({ x: e.clientX, y: e.clientY });
    
    // 计算鼠标相对于元素的偏移
    const rect = e.currentTarget.getBoundingClientRect();
    setDragOffset({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    });
  };

  const handleMouseMove = (e) => {
    if (!mouseDown || draggedItem === null) return;
    
    const deltaX = Math.abs(e.clientX - dragStartPos.x);
    const deltaY = Math.abs(e.clientY - dragStartPos.y);
    
    // 只有移动距离超过阈值才开始拖拽
    if (deltaX > dragThreshold || deltaY > dragThreshold) {
      if (!isDragging) {
        setIsDragging(true);
        // 添加拖拽样式
        document.body.style.cursor = 'grabbing';
        document.body.style.userSelect = 'none';
        
        // 创建拖拽预览内容
        const draggedItemData = displayImages.find(item => item.displayIndex === draggedItem);
        if (draggedItemData) {
          setDragPreview({
            show: true,
            x: e.clientX - dragOffset.x,
            y: e.clientY - dragOffset.y,
            content: draggedItemData
          });
        }
      } else {
        // 更新拖拽预览位置
        setDragPreview(prev => ({
          ...prev,
          x: e.clientX - dragOffset.x,
          y: e.clientY - dragOffset.y
        }));
      }
      
      // 检测拖拽悬停目标
      const elementBelow = document.elementFromPoint(e.clientX, e.clientY);
      if (elementBelow) {
        const layerItem = elementBelow.closest('[data-layer-index]');
        if (layerItem) {
          const targetIndex = parseInt(layerItem.getAttribute('data-layer-index'));
          if (targetIndex !== draggedItem && targetIndex !== dragOverIndex) {
            setDragOverIndex(targetIndex);
          }
        } else {
          setDragOverIndex(null);
        }
      }
    }
  };

  const handleMouseUp = (e) => {
    if (!mouseDown) return;
    
    setMouseDown(false);
    document.body.style.cursor = '';
    document.body.style.userSelect = '';
    
    if (isDragging && draggedItem !== null && dragOverIndex !== null && draggedItem !== dragOverIndex) {
      // 执行拖拽操作
      handleDrop(draggedItem, dragOverIndex);
    }
    
    // 重置状态
    setIsDragging(false);
    setDraggedItem(null);
    setDragOverIndex(null);
    setDragPreview({ show: false, x: 0, y: 0, content: null });
  };

  // 处理拖拽完成的逻辑
  const handleDrop = (fromDisplayIndex, toDisplayIndex) => {
    if (fromDisplayIndex === toDisplayIndex) return;
    
    if (onReorderImages) {
      // 将显示索引转换为原始数组索引
      const fromOriginalIndex = layerImages.length - 1 - fromDisplayIndex;
      const toOriginalIndex = layerImages.length - 1 - toDisplayIndex;
      onReorderImages(fromOriginalIndex, toOriginalIndex);
      
      // 拖拽完成后，选中被拖拽的元素
      // 先获取被拖拽元素的信息
      const draggedItemData = displayImages.find(item => item.displayIndex === fromDisplayIndex);
      
      if (draggedItemData) {
        // 延迟设置选中状态，确保数组重排序完成
        setTimeout(() => {
          // 重新获取更新后的displayImages
          const updatedDisplayImages = layerImages.map((item, arrayIndex) => {
            return {
              id: `layer-${item.id}`, 
              originalIndex: arrayIndex,
              fileName: item.fileName,
              src:item.src
            };
          }).reverse().map((item, displayIndex) => ({
            ...item,
            displayIndex
          }));
          
          // 找到被拖拽元素在新位置的信息（通过src匹配）
          const movedItem = updatedDisplayImages.find(item => item.src === draggedItemData.src);
          if (movedItem) {
            setSelectedIndex(movedItem.id);
            onLayerImageClick && onLayerImageClick(movedItem.originalIndex);
          }
        }, 0);
      }
    }
  };

  // 添加全局鼠标事件监听
  useEffect(() => {
    if (mouseDown) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      
      return () => {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
      };
    }
  }, [mouseDown, draggedItem, isDragging, dragStartPos, dragOverIndex]);

  // 旧的拖拽事件处理函数已被鼠标事件替代，这里保留注释作为参考
  // 现在使用 handleMouseDown, handleMouseMove, handleMouseUp 来处理拖拽

  const handleItemClick = (item) => {
    // 如果正在拖拽，不触发点击事件
    if (isDragging) {
      return;
    }
    // 直接设置选中状态，不需要通过handleImageClick重复设置
    setSelectedIndex(item.id);
    // 只调用外部回调，传递原始索引
    onLayerImageClick && onLayerImageClick(item.originalIndex);
  };

  return (
    <div className={styles.history}>
      <div className={styles.historyContainer} style={{flex:'1'}}>
        <div className={styles.title}>图层</div>
        {displayImages.map((item, index) => (
          <div 
            key={item.id}
            data-layer-index={item.displayIndex}
            className={`${styles.historyItem} ${
              selectedIndex === item.id ? styles.selected : ''
            } ${
              draggedItem === item.displayIndex ? styles.dragging : ''
            } ${
              dragOverIndex === item.displayIndex && draggedItem !== item.displayIndex ? styles.dragOver : ''
            }`}
            onClick={() => handleItemClick(item)}
            onMouseDown={(e) => {
              setDraggedItem(item.displayIndex);
              handleMouseDown(e, item.displayIndex);
            }}
            style={{
              opacity: draggedItem === item.displayIndex ? 0.3 : 1,
              cursor: isDragging && draggedItem === item.displayIndex ? 'grabbing' : 'grab',
              transform: draggedItem === item.displayIndex ? 'rotate(5deg) scale(1.05)' : 'none',
              zIndex: draggedItem === item.displayIndex ? 1000 : 'auto',
              userSelect: 'none' // 防止文本选择
            }}
          >
            <Image 
              className={styles.img} 
              src={item.src} 
              preview={false} 
              draggable={false} 
            />
            <div className={styles.imgName} title={item.fileName}>{item.fileName}</div>
            <div className={styles.tool} >
              <Image 
                className={styles.toolIcon}
                src={deleteIcon} 
                preview={false} 
                draggable={false} 
              />
              <Image 
                className={styles.toolIcon}
                src={download} 
                preview={false} 
                draggable={false} 
              />
            </div>
          </div>
        ))}
        {/* 拖拽预览元素 */}
      {dragPreview.show && dragPreview.content && (
        <div 
          className={`${styles.historyItem} ${styles.selected}`}
          style={{
            position: 'fixed',
            left: dragPreview.x,
            top: dragPreview.y,
            zIndex: 9999,
            pointerEvents: 'none',
            opacity: 0.5,
            transition: 'none',
            cursor: 'grabbing',
            userSelect: 'none'
          }}
        >
          <Image 
            className={styles.img} 
            src={dragPreview.content.src} 
            preview={false} 
            draggable={false}
          />
          <div className={styles.imgName}>{dragPreview.content.fileName}</div>
          <div className={styles.tool}>
            <Image 
              className={styles.toolIcon}
              src={deleteIcon} 
              preview={false}
              draggable={false}
            />
            <Image 
              className={styles.toolIcon}
              src={download} 
              preview={false}
              draggable={false}
            />
          </div>
        </div>
      )}
      </div>
      <Button className={`button buttonPrimary ${styles.submitButton}`} onClick={onCompositeClick}>
        合成
      </Button>
    </div>
  );
}